package com.uduemc.biso.node.web.api.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.HRepertoryLabel;
import com.uduemc.biso.node.core.entities.HSSL;
import com.uduemc.biso.node.core.node.extities.RepertoryLabelTableData;
import com.uduemc.biso.node.core.utils.FilterResponse;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.pojo.ResponseRepertory;
import com.uduemc.biso.node.web.api.service.DomainService;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.api.service.WebSiteService;

import cn.hutool.core.collection.CollUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/api/repertory")
@Api(tags = "资源库管理模块")
public class RepertoryController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private RepertoryService repertoryServiceImpl;

	@Autowired
	private DomainService domainServiceImpl;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private WebSiteService webSiteServiceImpl;

	@PostMapping("/all-label")
	public JsonResult allLabel() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		List<HRepertoryLabel> currentAllRepertoryLabel = repertoryServiceImpl.getCurrentAllRepertoryLabel();
		return JsonResult.ok(currentAllRepertoryLabel);
	}

	/**
	 * 获取非回收站内的资源列表数
	 * 
	 * @param responseRepertory
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@ApiOperation(value = "资源数据列表", notes = "通过参数过滤查询资源数据列表")
	@PostMapping("/find")
	public JsonResult find(@Valid @RequestBody ResponseRepertory responseRepertory, BindingResult errors)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (errors.hasErrors()) {
			for (FieldError fieldError : errors.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				String field = fieldError.getField();
				logger.info("field: " + field + "defaultMessage: " + defaultMessage);
				return JsonResult.messageError(field + " " + defaultMessage);
			}
		}
		PageInfo<HRepertory> data = repertoryServiceImpl.getCurrentAndResponseRepertory(responseRepertory);
		// 过滤数据中的敏感信息
		List<HRepertory> list = data.getList();
		List<HRepertory> responseList = new ArrayList<HRepertory>();
		for (HRepertory hRepertory : list) {
			hRepertory.setFilepath("");
			hRepertory.setZoompath("");
			hRepertory.setUnidname("");
			responseList.add(hRepertory);
		}
		data.setList(responseList);
		return JsonResult.ok(data);
	}

	@PostMapping("/find-refuse")
	public JsonResult findRefuse(@Valid @RequestBody ResponseRepertory responseRepertory, BindingResult errors)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (errors.hasErrors()) {
			for (FieldError fieldError : errors.getFieldErrors()) {
				String defaultMessage = fieldError.getDefaultMessage();
				String field = fieldError.getField();
				logger.info("field: " + field + "defaultMessage: " + defaultMessage);
				return JsonResult.messageError(field + " " + defaultMessage);
			}
		}
		PageInfo<HRepertory> data = repertoryServiceImpl.getCurrentAndResponseRepertoryRefuse(responseRepertory);
		// 过滤数据中的敏感信息
		List<HRepertory> list = data.getList();
		List<HRepertory> responseList = new ArrayList<HRepertory>();
		for (HRepertory hRepertory : list) {
			hRepertory.setFilepath("");
			hRepertory.setZoompath("");
			hRepertory.setUnidname("");
			responseList.add(hRepertory);
		}
		data.setList(responseList);
		return JsonResult.ok(data);
	}

	@PostMapping("/update-label")
	public JsonResult updateLabel(@RequestParam("id") long id, @RequestParam("labelId") long labelId)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1 || labelId < 0) {
			return JsonResult.illegal();
		}
		HRepertory hRepertory = repertoryServiceImpl.getInfoByid(id);
		if (hRepertory == null || hRepertory.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
			return JsonResult.illegal();
		}
		if (labelId > 0) {
			HRepertoryLabel hRepertoryLabel = repertoryServiceImpl.getInfoByIdHostId(labelId, requestHolder.getHost().getId().longValue());
			if (hRepertoryLabel == null) {
				return JsonResult.illegal();
			}
		}
		hRepertory.setLabelId(labelId);
		HRepertory data = repertoryServiceImpl.updateById(hRepertory);
		data.setFilepath("");
		data.setZoompath("");
		data.setUnidname("");
		return JsonResult.messageSuccess("修改成功", data);
	}

	@PostMapping("/delete")
	public JsonResult delete(@RequestParam("id") long id) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1) {
			return JsonResult.illegal();
		}
		HRepertory data = repertoryServiceImpl.getInfoByid(id);
		if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
			logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue());
			return JsonResult.illegal();
		}
		// 开始进行删除操作
		if (!repertoryServiceImpl.delete(id)) {
			return JsonResult.illegal();
		}
		return JsonResult.messageSuccess("删除成功", FilterResponse.filterRepertoryInfo(data));
	}

	@PostMapping("/delete-list")
	public JsonResult deleteList(@RequestBody List<Long> ids) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (ids.size() < 0) {
			return JsonResult.illegal();
		}
		List<HRepertory> datas = new ArrayList<>();
		for (long id : ids) {
			HRepertory data = repertoryServiceImpl.getInfoByid(id);
			if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
				logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue());
				return JsonResult.illegal();
			}
			datas.add(data);
		}

		if (!repertoryServiceImpl.delete(ids)) {
			return JsonResult.illegal();
		}
		return JsonResult.messageSuccess("删除成功", FilterResponse.filterRepertoryInfoListHRepertory(datas));
	}

	/**
	 * 资源标签table表展示的标签
	 */
	@PostMapping("/all-label-for-tabledata")
	public JsonResult allLabelForTabledata() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		List<RepertoryLabelTableData> data = repertoryServiceImpl.getCurrentAllLabelForTabledata();
		return JsonResult.ok(data);
	}

	/**
	 * 保存 标签
	 * 
	 * @return
	 * @throws IOException
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 */
	@PostMapping("/label-save")
	public JsonResult labelSave(@RequestParam("id") long id, @RequestParam("name") String name)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 0) {
			return JsonResult.illegal();
		}
		if (!StringUtils.hasText(name)) {
			return JsonResult.illegal();
		}
		if (name.length() > 100) {
			return JsonResult.messageError("标签名不能超过100个字符");
		}

		List<RepertoryLabelTableData> data = repertoryServiceImpl.getCurrentAllLabelForTabledata();
		if (id == 0 && data.size() >= 50) {
			return JsonResult.messageError("最多只有50个标签！");
		}

		HRepertoryLabel labelSave = repertoryServiceImpl.labelSave(id, name);
		if (labelSave == null) {
			return JsonResult.illegal();
		}
		return JsonResult.messageSuccess(labelSave);
	}

	/**
	 * 删除标签需要将原来数据该标签的资源重置为未定义
	 * 
	 * @param id
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/label-delete")
	public JsonResult labelDelete(@RequestParam("id") long id) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1) {
			return JsonResult.illegal();
		}
		HRepertoryLabel hRepertoryLabel = repertoryServiceImpl.getInfoByIdHostId(id, requestHolder.getHost().getId().longValue());
		if (hRepertoryLabel == null || hRepertoryLabel.getType().shortValue() != (short) 0) {
			return JsonResult.illegal();
		}
		boolean bool = repertoryServiceImpl.labelDelete(hRepertoryLabel);
		if (!bool) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("删除成功", hRepertoryLabel);
	}

	/**
	 * 还原回收站内的资源
	 * 
	 * @param id
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/reduction-item")
	public JsonResult reductionItem(@RequestParam("id") long id) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1) {
			return JsonResult.illegal();
		}
		HRepertory data = repertoryServiceImpl.getInfoByid(id);
		if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue() || data.getIsRefuse().shortValue() != (short) 1) {
			logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue()
					+ " 或者要还原的数据根本不在回收站中! isRefuse: " + data.getIsRefuse());
			return JsonResult.illegal();
		}
		// 还原
		if (!repertoryServiceImpl.reductionItem(data)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("还原成功", FilterResponse.filterRepertoryInfo(data));
	}

	@PostMapping("/reduction-items")
	public JsonResult reductionItems(@RequestBody List<Long> ids) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (CollectionUtils.isEmpty(ids)) {
			return JsonResult.illegal();
		}
		List<HRepertory> listHRepertory = new ArrayList<>();
		for (Long id : ids) {
			if (id == null || id.longValue() < 1) {
				return JsonResult.illegal();
			}
			HRepertory data = repertoryServiceImpl.getInfoByid(id);
			if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue() || data.getIsRefuse().shortValue() != (short) 1) {
				logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue()
						+ " 或者要还原的数据根本不在回收站中! isRefuse: " + data.getIsRefuse());
				return JsonResult.illegal();
			}
			listHRepertory.add(data);
		}
		// 还原
		if (!repertoryServiceImpl.reductionItems(ids)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("还原成功", FilterResponse.filterRepertoryInfoListHRepertory(listHRepertory));
	}

	@PostMapping("/reduction-all")
	public JsonResult reductionAll() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		// 还原
		if (!repertoryServiceImpl.reductionCurrentAll()) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("全部还原成功");
	}

	@PostMapping("/clear-item")
	public JsonResult clearItem(@RequestParam("id") long id) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1) {
			return JsonResult.illegal();
		}
		HRepertory data = repertoryServiceImpl.getInfoByid(id);
		if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue() || data.getIsRefuse().shortValue() != (short) 1) {
			logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue()
					+ " 或者要还原的数据根本不在回收站中! isRefuse: " + data.getIsRefuse());
			return JsonResult.illegal();
		}

		Short type = data.getType();
		if (type != null && type.shortValue() == (short) 6) {
			List<HSSL> listHSSL = domainServiceImpl.infosSSLByRepertoryId(data.getId());
			if (CollUtil.isNotEmpty(listHSSL)) {
				return JsonResult.messageError("域名已绑定的SSL证书不能清除，请先删除绑定的SSL证书后再进行清除！");
			}
		}

		List<Long> ids = new ArrayList<>();
		ids.add(id);

		if (!repertoryServiceImpl.clearItems(ids)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("彻底删除成功", FilterResponse.filterRepertoryInfo(data));
	}

	@PostMapping("/clear-items")
	public JsonResult clearItems(@RequestBody List<Long> ids) throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (CollectionUtils.isEmpty(ids)) {
			return JsonResult.illegal();
		}
		List<HRepertory> listHRepertory = new ArrayList<>();
		for (Long id : ids) {
			if (id == null || id.longValue() < 1) {
				return JsonResult.illegal();
			}
			HRepertory data = repertoryServiceImpl.getInfoByid(id);
			if (data == null || data.getHostId().longValue() != requestHolder.getHost().getId().longValue() || data.getIsRefuse().shortValue() != (short) 1) {
				logger.error("通过id获取的HRepertory数据不存在或者获取的数据不是当前hostId id:" + id + " hostId:" + requestHolder.getHost().getId().longValue()
						+ " 或者要还原的数据根本不在回收站中! isRefuse: " + data.getIsRefuse());
				return JsonResult.illegal();
			}

			Short type = data.getType();
			if (type != null && type.shortValue() == (short) 6) {
				List<HSSL> listHSSL = domainServiceImpl.infosSSLByRepertoryId(data.getId());
				if (CollUtil.isNotEmpty(listHSSL)) {
					return JsonResult.messageError("域名已绑定的SSL证书不能清除，请先删除绑定的SSL证书后再进行清除！");
				}
			}

			listHRepertory.add(data);
		}

		if (!repertoryServiceImpl.clearItems(ids)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("彻底删除成功", FilterResponse.filterRepertoryInfoListHRepertory(listHRepertory));
	}

	@PostMapping("/clear-all")
	public JsonResult clearAll() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		JsonResult clearCurrentAll = repertoryServiceImpl.clearCurrentAll();
		if (clearCurrentAll != null) {
			return clearCurrentAll;
		}
		return JsonResult.messageSuccess("全部彻底删除成功");
	}

	@PostMapping("/add-outside-image-link")
	public JsonResult insertOutsideImageLink(@RequestParam("link") String link)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StringUtils.isEmpty(link)) {
			return JsonResult.illegal();
		}

		HRepertory hRepertory = repertoryServiceImpl.insertCurrentOutsideImageLink(link);
		if (hRepertory == null) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(FilterResponse.filterRepertoryInfo(hRepertory));
	}

	@PostMapping("/update-repertory-oname")
	public JsonResult updateRepertoryOname(@RequestParam("id") long id, @RequestParam("name") String name, @RequestParam("oname") String oname)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (id < 1 || StringUtils.isEmpty(oname)) {
			return JsonResult.illegal();
		}
		if (oname.length() > 120) {
			return JsonResult.messageError("资源名过长，长度不能超过120");
		}
		JsonResult jsonResult = repertoryServiceImpl.updateCurrentOriginalFilename(id, oname);
		if (jsonResult == null) {
			return JsonResult.assistance();
		}

		// 清理页面内容缓存
		webSiteServiceImpl.cacheCurrentHostClear();
		return jsonResult;
	}

	/**
	 * 返回资源类型的总数
	 * 
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	@PostMapping("/total-type")
	public JsonResult totalType() throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		int totalImg = repertoryServiceImpl.totalCurrentType((short) 0);
		int totalFile = repertoryServiceImpl.totalCurrentType((short) 1);
		int totalFlash = repertoryServiceImpl.totalCurrentType((short) 2);
		int totalMP3 = repertoryServiceImpl.totalCurrentType((short) 3);
		int totalLink = repertoryServiceImpl.totalCurrentType((short) 4);
		int totalMP4 = repertoryServiceImpl.totalCurrentType((short) 5);
		int ssl = repertoryServiceImpl.totalCurrentType((short) 6);

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("img", totalImg);
		resultMap.put("file", totalFile);
		resultMap.put("flash", totalFlash);
		resultMap.put("mp3", totalMP3);
		resultMap.put("link", totalLink);
		resultMap.put("mp4", totalMP4);
		resultMap.put("ssl", ssl);

		return JsonResult.ok(resultMap);
	}

	/**
	 * 通过传入一个外部链接的数组，生成一个对应数组为key，资源数据为值的 map
	 * 
	 * @param externalLinks
	 * @return
	 */
	@PostMapping("/make-external-links")
	public JsonResult makeExternalLinks(@RequestBody List<String> externalLinks)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		Map<String, HRepertory> resultMap = repertoryServiceImpl.makeExternalLinks(externalLinks);
		return JsonResult.ok(resultMap);
	}
}
